<?php

namespace app\common\model;

use think\Model;


class GoodsHospital extends Model
{

    

    

    // 表名
    protected $name = 'goods_hospital';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    

    







    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function hospital()
    {
        return $this->belongsTo('Hospital', 'hospital_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function addhospital($hospitals,$goods_id){
        $hastime=self::where(['goods_id'=>$goods_id])->select();
        $hospitals_a=[];
        foreach($hospitals as $k=>$v){
            $hospitals_a[$k]['hospital_id']=$v;
        }
        foreach($hastime as $k5=>$v5){
            $qhas=0;

            foreach($hospitals as $k=>$v){
                $hospitals_a[$k]['hospital_id']=$v;
                    if($v5['hospital_id']==$v){
                        $qhas=1;
                        $hospitals_a[$k]['select_hospital_id'] = $v5['id'];
                    }

                // $resume_id[]=$v['file_id'];
            }
            if($qhas==0){
                self::destroy(['id' => $v5['id']]);
            }
        }

        foreach($hospitals_a as  $k=>$v){

            if(isset($v['select_hospital_id'])){
                //判断当前是否存在对应时间
                $selecthospital_id=self::where(['id'=>$v['select_hospital_id']])->find();
                if($selecthospital_id){
                    $selecthospital_id->hospital_id= $v['hospital_id'];
                    $selecthospital_id->updatetime=time();
                    $selecthospital_id->save();
                }
            }else{
                $data=[
                    'hospital_id'=>$v['hospital_id'],
                    'goods_id'=>$goods_id,
                    'createtime'	=>time(),
                    'updatetime'=>time(),
                ];
                self::insertGetid($data);
            }


        }
    }
}
